#!/bin/bash

# 日志文件
LOG_FILE="/root/update_all_services.log"

exec > >(tee -a ${LOG_FILE}) 2>&1

# Function to log and execute commands
log_and_execute() {
    echo "Executing: $@" | tee -a ${LOG_FILE}
    "$@" | tee -a ${LOG_FILE}
}

# Function to wait for dpkg lock
wait_for_dpkg_lock() {
    while sudo fuser /var/lib/dpkg/lock-frontend >/dev/null 2>&1 || sudo fuser /var/lib/dpkg/lock >/dev/null 2>&1; do
        echo "Waiting for other package management process to finish..." | tee -a ${LOG_FILE}
        sleep 5
    done
}

# Function to check Apache configuration
check_apache_config() {
    log_and_execute sudo apache2ctl configtest
    if ! sudo apache2ctl configtest | grep -q "Syntax OK"; then
        echo "There is a syntax error in the Apache configuration. Please check the output above for details." | tee -a ${LOG_FILE}
        sudo tail -n 50 /var/log/apache2/error.log | tee -a ${LOG_FILE}
        #exit 1
    fi
}

# 确保所有必要服务在启动时自动启动
SERVICES=("apache2" "mysql" "php7.4-fpm" "ufw")

for SERVICE in "${SERVICES[@]}"; do
    log_and_execute sudo systemctl enable $SERVICE
    log_and_execute sudo systemctl start $SERVICE
done

# 检查并修复Apache配置
check_apache_config

# 重新加载防火墙规则
log_and_execute sudo ufw reload

# 验证服务状态
for SERVICE in "${SERVICES[@]}"; do
    if sudo systemctl is-active $SERVICE | grep -q "active"; then
        echo "$SERVICE service is running." | tee -a ${LOG_FILE}
    else
        echo "$SERVICE service is not running. Please check the installation." | tee -a ${LOG_FILE}
    fi
done

# 配置 suno-api systemd 服务
SERVICE_FILE="/etc/systemd/system/suno-api.service"

cat <<EOF | sudo tee $SERVICE_FILE
[Unit]
Description=Suno API Service
After=network.target

[Service]
ExecStart=/usr/bin/npm run dev --prefix /root/suno-api
WorkingDirectory=/root/suno-api
Restart=always
RestartSec=10
User=root
Environment=PATH=/usr/bin:/usr/local/bin
Environment=NODE_ENV=production

[Install]
WantedBy=multi-user.target
EOF

# 重新加载 systemd 配置
log_and_execute sudo systemctl daemon-reload

# 启动并启用 suno-api 服务
log_and_execute sudo systemctl enable suno-api
log_and_execute sudo systemctl start suno-api

# 检查服务状态
if sudo systemctl is-active suno-api | grep -q "active"; then
    echo "suno-api service is running." | tee -a ${LOG_FILE}
else
    echo "suno-api service is not running. Please check the installation." | tee -a ${LOG_FILE}
fi

echo "All services have been updated and verified." | tee -a ${LOG_FILE}
